package com.ejuornal.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.ejuornal.bean.Page;
import com.ejuornal.bean.PermissionGroup;
import com.ejuornal.dao.PermissionGroupDAO;
@Component("permissionGroupDao")
public class PermissionGroupDAOImpl extends DaoSupport<PermissionGroup> implements PermissionGroupDAO{

    @Override
    public void add(String sql, Object... objs) {
        super.add(sql, objs);
    }

    @Override
    public void update(String sql, Object... objs) {
        // TODO Auto-generated method stub
        super.update(sql, objs);
    }

    @Override
    public Page<PermissionGroup> find(int current_record, String url) {
        return super.find(current_record, url);
    }
    
    public boolean delete(int pgId) {
        String sql = "delete from t_permission_group where pgId=? cascade";
        int num = super.getJdbcTemplate().update(sql, pgId);
        if(num >0) {
            return true;
        }
        return false;
    }

	@Override
	public boolean batchUpdate() {
		final List<String> pgNames = new ArrayList<String>();
		pgNames.add("会员管理");
		pgNames.add("管理员管理");
		pgNames.add("消息管理");
		pgNames.add("期刊管理");
		pgNames.add("权限管理");
		pgNames.add("系统管理");
		pgNames.add("广告管理");
		pgNames.add("期刊分类管理");
		pgNames.add("评论管理");
		String sql ="insert into t_permission_group(pgId, pgName) value(?,?)";
		getJdbcTemplate().batchUpdate(sql, 
				 new BatchPreparedStatementSetter(){
					@Override
					public int getBatchSize() {
						return 0;
					}
					@Override
					public void setValues(PreparedStatement ps, int i)
							throws SQLException {
						ps.setInt(1, i+1);
						ps.setString(2, pgNames.get(i));
					}
				}
				);
		return true;
	}

	@Override
	public List<PermissionGroup> findNamesByRoleId(int roleId) {
		String sql = "select t1.pgId, t1.pgName from t_permission_group t1 where t1.pgId in(select distinct t2.pgId from t_permission t2, t_role_permission t3 where t2.pid = t3.pid and t3.roleId=?)";
		List<PermissionGroup> str = getJdbcTemplate().query(
				sql, 
				new Object[]{roleId},
				new RowMapper() {
					@Override
					public Object mapRow(ResultSet rs, int arg1)
							throws SQLException {
						PermissionGroup pg = new PermissionGroup();
						pg.setPgId(rs.getInt("pgId"));
						pg.setPgName(rs.getString("pgName"));
						return pg;
					}
					
				}
				);
		return str;
	}
    
}
